package com.jwyming.secKilling;


import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.concurrent.Callable;



public class SecKillingTask implements Callable<String> {
    Logger logger = Logger.getLogger(this.getClass().getName());

    private int executeTimes;
    private ConfigItem configItem;

    public SecKillingTask(int executeTimes, ConfigItem configItem) {
        this.executeTimes = executeTimes;
        this.configItem = configItem;
    }

    public String call() throws Exception {
        return runSecKilling();
    }

    private String runSecKilling() {
        String result = "Fail";

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                    boolean isRedirect = false;
                    try {
                        isRedirect = super.isRedirected(request, response, context);
                    } catch (ProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (!isRedirect) {
                        int responseCode = response.getStatusLine().getStatusCode();
                        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                                || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                            return true;
                        }
                    }
                    return isRedirect;
                }
            });

            // 登录需要的信息
            String loginUrl = getUniformedUrl(configItem.getProperty("login.url"));
            String loginFormActionMatcher = configItem.getProperty("login.formActionMatcher");
            HashMap<String, Object> loginParams = configItem.getParams("login.params");


            // 选择产品需要的信息
            String productListUrl = getUniformedUrl(configItem.getProperty("product.listUrl"));
            String productFormActionMatcher = configItem.getProperty("product.formActionMatcher");
            HashMap<String, Object> productParams = configItem.getParams("product.params");


//            logger.info(Thread.currentThread().getName() + ":  开始秒杀...");
            logger.info(Thread.currentThread().getName() + ":  开始秒杀...");

            // 得到登录网页
            StringBuffer loginPageContent = Utils.getPageContent(httpclient, loginUrl);

            // 得到登录表单
            Form loginForm = Utils.getActionForm(loginPageContent, loginFormActionMatcher);


            // 更新登录表单信息
            loginForm.setActionUrl(getUniformedUrl(loginForm.getActionUrl()));
            loginForm = Utils.updateForm(loginForm, loginParams, 0);

            //        登录操作
            StringBuffer loggedMainPageContent = Utils.sendPost(httpclient,
                    loginForm.getActionUrl(), loginForm.getParams());


            //        logger.info("打印登录后首页里的URL。。。");
            //        Utils.printUrls(Utils.getUrls(loggedMainPageContent));


            // 得到产品列表网页
            StringBuffer productListPageContent = Utils.getPageContent(httpclient, productListUrl);

            // 得到产品表单
            Form productForm = Utils.getActionForm(productListPageContent, productFormActionMatcher);


            // 更新产品表单信息
            productForm.setActionUrl(getUniformedUrl(productForm.getActionUrl()));
            productForm = Utils.updateForm(productForm, productParams, executeTimes);

            //        提交产品操作
            StringBuffer submittedProductPageContent = Utils.sendPost(httpclient,
                    productForm.getActionUrl(), productForm.getParams());

//            logger.info("秒杀成功");

//            result = "Fail";
            result = "Success";


        } catch (Exception e) {
            e.printStackTrace();
            result = "Fail";
        }

        return result;
    }

    private String getUniformedUrl(String url) {
        String uniformedUrl = url;
        if(!uniformedUrl.startsWith("http")) {
            uniformedUrl = configItem.getProperty("DOMAIN_URL") + url;
        }
        return uniformedUrl;
    }




//    public DefaultHttpClient getHttpclient() {
//        return httpclient;
//    }
//
//    public void setHttpclient(DefaultHttpClient httpclient) {
//        this.httpclient = httpclient;
//    }
}
